package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/10/18.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";

    private LigDialog ligDialog;
    private String phone = "";
    private String from;
    private String mPushKey;

    private ImageView btForget;
    private ImageView btLogin;
    private EditText etPhone;
    private EditText etPassword;
    private TextView tvTitle;
    private TextView tvRight;
    private ImageView btLeft;
    private ImageView btWechat;
    private ImageView btWeibo;
    private ImageView btQQ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        KeyboardUtils.hideSoftInput(this);
        ShareSDK.initSDK(this);
        initView();
        mPushKey = JPushInterface.getRegistrationID(this);
        from = getIntent().getStringExtra("from");
        phone = SPUtils.getPref(this, UserInfo.PHONE, "");
        if (!TextUtils.isEmpty(phone)) {
            etPhone.setText(phone);
        }
    }

    private void initView() {
        btLogin = getView(R.id.bt_login);
        etPhone = getView(R.id.et_phone);
        etPassword = getView(R.id.et_password);
        tvTitle = getView(R.id.tv_title);
        tvTitle.setText(R.string.login_login);
        setZHTypeface(tvTitle);
        tvRight = getView(R.id.tv_right);
        tvRight.setText(R.string.login_register);
        tvRight.setTextColor(Color.parseColor("#FFFFFF"));
        tvRight.setVisibility(View.VISIBLE);
        btForget = getView(R.id.bt_forget);
        btLeft = getView(R.id.bt_left);
        btWechat = getView(R.id.bt_wechat);
        btWeibo = getView(R.id.bt_weibo);
        btQQ = getView(R.id.bt_qq);

        btLogin.setOnClickListener(this);
        tvRight.setOnClickListener(this);
        btForget.setOnClickListener(this);
        btLeft.setOnClickListener(this);
        btWechat.setOnClickListener(this);
        btWeibo.setOnClickListener(this);
        btQQ.setOnClickListener(this);
    }

    private void login() {
        if (TextUtils.isEmpty(etPhone.getText().toString())) {
            Toast.makeText(this, R.string.login_telephone_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(etPassword.getText().toString())) {
            Toast.makeText(this, R.string.login_pass_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        startLogin();
    }

    private void registe() {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    private void findPass() {
        startActivity(new Intent(this, FindPassActivity.class));
        finish();
    }

    private void qqLogin() {
        Log.i(TAG, "QQ Login...");
        Platform weibo = ShareSDK.getPlatform(QQ.NAME);
        weibo.setPlatformActionListener(platformActionListener);
        weibo.SSOSetting(false);
        weibo.showUser(null);
    }

    private void wechatLogin() {
        Platform weibo = ShareSDK.getPlatform(Wechat.NAME);
        weibo.setPlatformActionListener(platformActionListener);
        weibo.SSOSetting(false);
        weibo.showUser(null);
    }

    private void weiboLogin() {
        Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        weibo.setPlatformActionListener(platformActionListener);
        weibo.SSOSetting(false);
        weibo.showUser(null);
    }

    PlatformActionListener platformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            String mPlatform = "";
            Map mMap = new HashMap<String, String>();
            if (platform.getName().equals(SinaWeibo.NAME)) {
                mPlatform = "weibo";
            } else if (platform.getName().equals(Wechat.NAME)) {
                mPlatform = "weixin";
            } else if (platform.getName().equals(QQ.NAME)) {
                mPlatform = "qq";
            }
            String openid = platform.getDb().getUserId();
            String nickname = platform.getDb().getUserName();
            String avatar = platform.getDb().getUserIcon();
            String unionid = "";
            mMap.put("platform", mPlatform);
            mMap.put("openid", openid);
            mMap.put("nickname", nickname);
            mMap.put("avatar", avatar);
            if (mPlatform.equals("weixin")) {
                unionid = hashMap.get("unionid").toString();
            }
            mMap.put("unionid", unionid);
//            Log.i(TAG, "avatar=" + avatar + ";nickname=" + nickname + ";openid=" + openid + "mPlatform=" + mPlatform + ";platform=" + platform.getName());
            Message message = new Message();
            message.obj = mMap;
            handler.sendMessage(message);
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {

        }

        @Override
        public void onCancel(Platform platform, int i) {

        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HashMap<String, String> res = (HashMap<String, String>) msg.obj;
            String platform = res.get("platform");
            String openid = res.get("openid");
            String nickname = res.get("nickname");
            String avatar = res.get("avatar");
            String unionid = res.get("unionid");
            thirtylogin(avatar, nickname, openid, unionid, platform);
        }
    };

    private void startLogin() {
        String phone = etPhone.getText().toString();
        String password = etPassword.getText().toString();
        String url = Api.URL_USER_LOGIN + "?pushkey=" + mPushKey;
        Log.i(TAG, "url=" + url);
        OkHttpUtils
                .post()
                .url(url)
                .addParams("phone", phone)
                .addParams("password", password)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(LoginActivity.this, getString(R.string.login_doing));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(LoginActivity.this, R.string.login_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        resolveLoginRespose(response);
                    }
                });
    }

    private void thirtylogin(String avatar, String nickname, String openid, String unionid, String platform) {
        String url = Api.URL_USER_THIRTYLOGIN + "?pushkey=" + mPushKey;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("openid", openid)
                .addParams("unionid", unionid)
                .addParams("platform", platform)
                .addParams("nickname", nickname)
                .addParams("avatar", avatar)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(LoginActivity.this, getString(R.string.login_doing));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(LoginActivity.this, R.string.login_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        resolveLoginRespose(response);
                    }
                });
    }

    private void resolveLoginRespose(String response) {
        UserBean user = null;
        JSONObject jsonObject = null;
        int status = 0;
        try {
            jsonObject = new JSONObject(response);
            status = jsonObject.getInt("status");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (status == 1) {
            user = JSONUtils.requestDetail(response, "data", UserBean.class);
            ((MyApplication) getApplication()).setUser(user);
            SPUtils.setPref(this, UserInfo.LOGINHASH, user.getLoginhash());
            afterLogin();
            Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
            finish();
        }else if(status == -5){
            Toast.makeText(this,R.string.login_bind_phone,Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this,BindActivity.class));
            finish();
        } else {
            Toast.makeText(this, R.string.login_fail, Toast.LENGTH_SHORT).show();
        }
    }


    private void afterLogin() {
        setResult(Activity.RESULT_OK);
        EventBus.getDefault().post(new ChangeUserInfoEvent());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                login();
                break;
            case R.id.bt_left:
                finish();
                break;
            case R.id.tv_right:
                registe();
                break;
            case R.id.bt_forget:
                findPass();
                break;
            case R.id.bt_wechat:
                wechatLogin();
                break;
            case R.id.bt_weibo:
                weiboLogin();
                break;
            case R.id.bt_qq:
                qqLogin();
                break;
            default:
                break;
        }
    }
}